package com.it.commicity.controller.oss;

import com.it.commicity.common.Result;
import com.it.commicity.config.oss.OSSUtil;
import com.it.commicity.service.sys.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RequestMapping("/api")
@RestController
public class OssController {
    @Autowired
    private ISysUserService userService;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        filename = getFileName(filename);
        //上传OSS
        OSSUtil.upload(file.getInputStream(), filename);
//        System.err.println("OssController-upload->图片名称："+filename);
        //获得url
        String url = OSSUtil.getURL(filename);
        System.err.println(url);
        return Result.success(url);
    }

    private String getFileName(String filename) {
        // 获取文件后缀
        String fileExtension = "";
        if (filename != null && filename.contains(".")) {
            fileExtension = filename.substring(filename.lastIndexOf("."));
        }
        return UUID.randomUUID().toString() + fileExtension;
    }

    @GetMapping("/updateImg")
    public Result updateUserImageByUserId(String userId, @RequestParam("avatar") String image) {
        int i = userService.updateUserImageByUserId(userId, image);
        if (i < 0) {
            Result.fail("更新失败");
        }
        return Result.success();
    }
}
